<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="80px" class="searchform" inline>
        <el-form-item label="产线名称" prop="url_map">
          <el-input
            v-model="listQuery.name"
            class="filter-item"
            placeholder="产线名称"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>

        <el-form-item :label="$t('bs.stream')" prop="cn_name">
          <el-select
            v-model="listQuery.importance"
            class="filter-item"
            clearable
            :placeholder="$t('bs.stream')"
            style="width: 90px;margin-left: 3px"
          >
            <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('bs.deviceName')" prop="url">
          <el-input
            v-model="listQuery.url"
            class="filter-item"
            :placeholder="$t('bs.deviceName')"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.departmentHead')" prop="url">
          <el-input
            v-model="listQuery.url"
            class="filter-item"
            placeholder="负责人"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.supplier')" prop="url">
          <el-input
            v-model="listQuery.url"
            class="filter-item"
            :placeholder="$t('bs.supplier')"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-button v-waves class="filter-item" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">
          {{ $t('table.add') }}
        </el-button>

      </el-form>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">-->
      <!--        {{ $t('table.export') }}-->
      <!--      </el-button>-->

    </div>
    <div style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;">
      <div style="display: flex;flex-direction: row;padding-bottom: 24px">
        <div style="flex: 1;display: flex;align-items: center">
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleCreate"
          >
            {{$t('bs.batchDelete')}}
          </el-button>
        </div>
        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
          <el-popover
            v-model="tablesetvisible"
            placement="bottom-start"
            width="160"
          >
            <div class="setcheckbox">
              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
              <el-checkbox v-for="(item,key) in fileds" :key="key" v-model="item.is_show" false-label="0" true-label="1">
                {{ item.title }}
              </el-checkbox>
            </div>
            <div slot="reference" class="hoverbutton">
              <img src="/static/table/fiter.png">
              <span style="margin-left: 8px;color: #666666">筛选</span>
            </div>
          </el-popover>
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        :span-method="arraySpanMethod"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        border
        default-expand-all
        fit
        highlight-current-row
        row-key="id"
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="名称">
          <template slot-scope="{$index,row}">
            <div v-if="($index+1)%4===0">
              <div>
                <el-table
                  :key="tableKey"
                  v-loading="listLoading"
                  :data="listb"
                  border
                  fit
                  highlight-current-row
                  style="width: 100%;"
                  @sort-change="sortChange"
                >
                  <el-table-column label="工位编号">
                    <template slot-scope="{row}">
                      <span>{{ row.id }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('bs.deviceName')">
                    <template slot-scope="{row}">
                      {{ row.name }}
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('bs.stream')">
                    <template slot-scope="{row}">
                      <span>{{ row.jzl }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('bs.departmentHead')">
                    <template slot-scope="{row}">
                      {{ row.fzr }}
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('bs.supplier')">
                    <template slot-scope="{row}">
                      {{ row.gys }}
                    </template>
                  </el-table-column>
                  <el-table-column label="当前版本">
                    <template slot-scope="{row}">
                      {{ row.dqbb }}
                    </template>
                  </el-table-column>

                  <el-table-column label="邮件发送状态">
                    <template slot-scope="{row}">
                      <el-tag type="warning">{{ row.yjzy }}</el-tag>
                    </template>
                  </el-table-column>

                  <el-table-column label="创建时间">
                    <template slot-scope="{row}">
                      <span>{{ row.day }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('table.actions')"
                    align="center"
                    class-name="small-padding fixed-width"
                    width="240"
                  >
                    <template slot-scope="{row,$index}">
                      <el-button size="mini" type="text" @click="handleUpdate(row)">
                        修改历史
                      </el-button>
                      <el-button v-if="row.status!='deleted'" size="mini" type="text">
                        历史版本
                      </el-button>
                      <el-button v-if="row.status!='deleted'" size="mini" type="text">
                        {{$t('bs.view')}}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <pagination
                  v-show="total>0"
                  :limit.sync="listQuery.limit"
                  :page.sync="listQuery.page"
                  :total="total"
                  @pagination="getList"
                />

              </div>

            </div>
            <div v-else style="display: inline">
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('bs.departmentType')">
          <template slot-scope="{row}">
            {{ row.bmnx }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('bs.departmentHead')">
          <template slot-scope="{row}">
            <span>{{ row.fzr }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="{row}">
            <span>{{ row.day }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :limit.sync="listQuery.limit" :page.sync="listQuery.page" :total="total" @pagination="getList" />
    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="上级产线" prop="type">
          <cy-tree-select v-model="temp.pid" :data="pdata" :props="{label:'name',children: 'children'}" />
        </el-form-item>
        <el-form-item label="编号" prop="title">
          <el-input v-model="temp.id" />
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="生产数量" prop="title">
          <el-input v-model="temp.num" />
        </el-form-item>
        <el-form-item label="生产时间" prop="timestamp">
          <el-date-picker v-model="temp.day" placeholder="请选择时间" type="datetime" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column label="Channel" prop="key" />
        <el-table-column label="Pv" prop="pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle, delArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'ComplexTable',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
    // typeFilter(type) {
    //   return calendarTypeKeyValue[type]
    // }
  },
  data() {
    return {
      pdata: [
        {
          id: 'xxxx-0001', name: 'xxx-0001', children: [
            { id: 'xxxx-0002', name: 'xxx-0002' }
          ]
        },
        {
          id: 'xxxx-0003', name: 'xxx-0003', children: [
            { id: 'xxxx-0004', name: 'xxx-0004' },
            { id: 'xxxx-0005', name: 'xxx-0005' }
          ]
        }
      ],
      listb: [
        {
          id: 'ST4000-2',
          name: '加重平衡',
          jzl: 'CngP/MSE-TS1',
          fzr: 'Li Can',
          gys: 'ED/MFT7',
          dqbb: '1.0',
          yjzy: '已发送',
          day: '2023-08-16'
        },

        {
          id: 'ST4000-2',
          name: '加重平衡',
          jzl: 'CngP/MSE-TS1',
          fzr: 'Li Can',
          gys: 'ED/MFT7',
          dqbb: '1.0',
          yjzy: '已发送',
          day: '2023-08-16'
        },
        {
          id: 'ST4000-2',
          name: '加重平衡',
          jzl: 'CngP/MSE-TS1',
          fzr: 'Li Can',
          gys: 'ED/MFT7',
          dqbb: '1.0',
          yjzy: '已发送',
          day: '2023-08-16'
        },
        {
          id: 'ST4000-2',
          name: '加重平衡',
          jzl: 'CngP/MSE-TS1',
          fzr: 'Li Can',
          gys: 'ED/MFT7',
          dqbb: '1.0',
          yjzy: '已发送',
          day: '2023-08-16'
        },
        {
          id: 'ST4000-2',
          name: '加重平衡',
          jzl: 'CngP/MSE-TS1',
          fzr: 'Li Can',
          gys: 'ED/MFT7',
          dqbb: '1.0',
          yjzy: '已发送',
          day: '2023-08-16'
        }
      ],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: ['CngP/MSE-TS1', 'CngP/MSE-TS2'],
      calendarTypeOptions,
      sortOptions: [{ label: '启用', key: '+id' }, { label: '禁用', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        day: '',
        pid: '',
        num: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      console.log('row', rowIndex)
      if ((rowIndex + 1) % 4 === 0) {
        if (columnIndex === 0) {
          return [1, 4]
        } else if (columnIndex === 1) {
          return [0, 0]
        }
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = [
          {
            id: 'aabb00001',
            name: 'CngP/MSE-TS',
            bmnx: '部门',
            fzr: 'Ye Mao',
            day: '2023-08-16',
            children: [{
              id: 'aabb00002',
              name: 'CngP/MSE-TS1',
              bmnx: '价值流',
              fzr: 'Ye Mao',
              day: '2023-08-16',
              children: [
                {
                  id: 'aabb00003',
                  name: 'GBM Module-2',
                  bmnx: '产线',
                  fzr: 'Ye Mao',
                  day: '2023-08-16',
                  children: [
                    {
                      id: 'aabb00004',
                      name: 'CngP/MSE-TS',
                      bmnx: '',
                      fzr: 'Ye Mao',
                      day: '2023-08-16'
                    }
                  ]
                }
              ]
            }]
          },
          {
            id: 'aabb00005',
            name: 'CngP/MSE-TS',
            bmnx: '部门',
            fzr: 'Ye Mao',
            day: '2023-08-16',
            children: [{
              id: 'aabb00006',
              name: 'CngP/MSE-TS1',
              bmnx: '价值流',
              fzr: 'Ye Mao',
              day: '2023-08-16',
              children: [
                {
                  id: 'aabb00007',
                  name: 'GBM Module-2',
                  bmnx: '产线',
                  fzr: 'Ye Mao',
                  day: '2023-08-16',
                  children: [
                    {
                      id: 'aabb00008',
                      name: 'CngP/MSE-TS',
                      bmnx: '',
                      fzr: 'Ye Mao',
                      day: '2023-08-16'
                    }
                  ]
                }
              ]
            }]
          },
          {
            id: 'aabb00009',
            name: 'CngP/MSE-TS',
            bmnx: '部门',
            fzr: 'Ye Mao',
            day: '2023-08-16',
            children: [{
              id: 'aabb00011',
              name: 'CngP/MSE-TS1',
              bmnx: '价值流',
              fzr: 'Ye Mao',
              day: '2023-08-16',
              children: [
                {
                  id: 'aabb00010',
                  name: 'GBM Module-2',
                  bmnx: '产线',
                  fzr: 'Ye Mao',
                  day: '2023-08-16',
                  children: [
                    {
                      id: 'aabb00012',
                      name: 'CngP/MSE-TS',
                      bmnx: '',
                      fzr: 'Ye Mao',
                      day: '2023-08-16'
                    }
                  ]
                }
              ]
            }]
          },
          {
            id: 'aabb00013',
            name: 'CngP/MSE-TS',
            bmnx: '部门',
            fzr: 'Ye Mao',
            day: '2023-08-16',
            children: [{
              id: 'aabb00014',
              name: 'CngP/MSE-TS1',
              bmnx: '价值流',
              fzr: 'Ye Mao',
              day: '2023-08-16',
              children: [
                {
                  id: 'aabb00015',
                  name: 'GBM Module-2',
                  bmnx: '产线',
                  fzr: 'Ye Mao',
                  day: '2023-08-16',
                  children: [
                    {
                      id: 'aabb00016',
                      name: 'CngP/MSE-TS',
                      bmnx: '',
                      fzr: 'Ye Mao',
                      day: '2023-08-16'
                    }
                  ]
                }
              ]
            }]
          }
        ]
        this.total = 10

        // Just to simulate the time of the request
        this.listLoading = false
      })
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)
      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          queryParma['and'] = [
            { field: listkeys[i], operator: 'like', value: '%' + this.listQuery[listkeys[i]] + '%' }
          ]
        }
      }
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.listQuery.where = {}
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      delArticle({ id: [row.id].join(',') }, 'sl_proline').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.searchform .el-form-item {
  margin-bottom: 0px !important;
}

.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}
</style>
